package com.atguigu.Base;

//线程 操作 资源类（filed+方法）

import java.util.concurrent.locks.ReentrantLock;

class Ticket1 {
    private int number = 50;
    ReentrantLock lock = new ReentrantLock(true);
    //ReentrantLock lock = new ReentrantLock();
    //lock本质AQS??     AbstractQueuedSynchronizer抽象队列同步器

    /**
     * public ReentrantLock() {
     *         sync = new NonfairSync();
     *     }
     * 根据源码所知它是非公平锁
     * 可重入锁+默认悲观锁
     */

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票，剩余" + number + "票");
            }
        } finally {
            lock.unlock();
        }
    }
}

public class SaleTicketDemoV2 {
   static Ticket1 ticket = new Ticket1();
   public static void main(String[] args) {
     new Thread(() -> {for (int i = 0; i <= 50; i++) ticket.sale();}, "A").start();
     new Thread(() -> {for (int i = 0; i <= 50; i++) ticket.sale();}, "B").start();
     new Thread(() -> {for (int i = 0; i <= 50; i++) ticket.sale();}, "C").start();
   }
}